﻿using System.Collections.Generic;
using System.Linq;
using Apps.Web.Core;
using Apps.IBLL.LMS;
using Apps.Locale;
using System.Web.Mvc;
using Apps.Common;
using Apps.IBLL;
using Microsoft.Practices.Unity;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Data;
using Apps.Models;
using Apps.Models.Flow;
using Apps.IBLL.Flow;
using Apps.Models.Enum;
using Apps.Models.Sys;
using Apps.IBLL.Sys;
using System.Configuration;
using Apps.BLL.YANX;
using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using Apps.Models.HuaChan;
using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.Office2013.Drawing.ChartStyle;
using Senparc.Weixin.MP.AdvancedAPIs.MerChant;
using static org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi;
using Wantn.FIS.Enum;
using Apps.Models.CustomModels;
using Apps.BLL.SelfRcRelated;
using Apps.BLL.LMS;

namespace Apps.Web.Areas.LMS.Controllers
{
    public class TestDataAuditController : BaseController
    {
        [Dependency]
        public ILMS_TESTDATA_AUDITBLL m_BLL { get; set; }

        [Dependency]
        public ILMS_TESTDATA_CONFIRMEDBLL m_cBLL { get; set; }
        [Dependency]
        public ISysUserBLL userBLL { get; set; }

        [Dependency]
        public IFlow_FormBLL formBLL { get; set; }

        [Dependency]
        public IFlow_FormContentBLL formContentBLL { get; set; }

        [Dependency]
        public IFlow_StepBLL stepBLL { get; set; }

        [Dependency]
        public IFlow_FormContentStepCheckBLL stepCheckBLL { get; set; }
        [Dependency]
        public ILMS_TESTDATA_AUDITBLL m_testdataBLL { get; set; }
        [Dependency]
        public IFlow_FormContentStepCheckStateBLL stepCheckStateBLL { get; set; }

        ValidationErrors errors = new ValidationErrors();

        [SupportFilter]
        public ActionResult RelatedList()
        {
            ViewBag.UserID = GetUserId();
            return View();
        }

        [SupportFilter]
        public ActionResult Index(int tuihui = 0)
        {
            ViewBag.UserID = GetUserId();
            ViewBag.Tuihui = tuihui;
            return View();
        }


        [SupportFilter]
        public ActionResult Tuihui(string TEST_CODE)
        {
            ViewBag.UserID = GetUserId();
            ViewBag.TEST_CODE = TEST_CODE;
            return View();
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Tuihui(string testCode,string ty="")
        {
            try
            {
                if (string.IsNullOrEmpty(testCode))
                    return Json(JsonHandler.CreateMessage(1, "参数错误"));
                string result = m_testdataBLL.TuiHuiAuditData(testCode);
                if (string.IsNullOrEmpty(result))
                {
                    return Json(JsonHandler.CreateMessage(1, "操作成功"));
                }
                else
                {
                    return Json(JsonHandler.CreateMessage(0, "操作失败" + result));
                }
            }
            catch
            {
                return Json(JsonHandler.CreateMessage(0, "审核失败"));
            }
        }


        [HttpPost]
        [SupportFilter(ActionName = "Index")]
        public JsonResult GetFlowList()
        {
            int totalCount = 0;
            List<TestDataOutPutModel> list = m_testdataBLL.GetSugarList(new Models.CustomModels.TestDataQuertParaModel
            {
                BatchCode = Utils.ObjectToStr(Request["BatchCode"]),
                BatchType = Utils.ObjectToStr(Request["BatchType"]),
                EndDate = Utils.ObjectToStr(Request["EndDate"]),
                MaterielName = Utils.ObjectToStr(Request["MaterielName"]),
                PageIndex = Utils.ObjToInt(Request["page"], 1),
                PageSize = Utils.ObjToInt(Request["rows"], 15),
                StartDate = Utils.ObjectToStr(Request["StartDate"]),
                TestCode = Utils.ObjectToStr(Request["TestCode"]),
                TypeStr = Utils.ObjectToStr(Request["TypeStr"]),
                ApprovalStatus = Utils.ObjToInt(Request["ApprovalStatus"], -1),
            }, ref totalCount);
            if (list != null)
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        //if (list[i].BATCH_TYPE == "入厂煤")
                        //{
                        //    list[i].CSR = list[i].SELF_CSR;
                        //    list[i].CRI = list[i].SELF_CRI;
                        //    if (!string.IsNullOrEmpty(list[i].SELF_YANX_VALUE))
                        //        list[i].YANX_VALUE = list[i].SELF_YANX_VALUE;
                        //}
                        //list[i].CRI = Utils.ToOnePoint(list[i].CRI);
                        //list[i].CSR = Utils.ToOnePoint(list[i].CSR);
                        //if (!string.IsNullOrEmpty(list[i].SELF_CSR))
                        //    list[i].CRI = Utils.ToOnePoint(list[i].CRI);
                        //if (!string.IsNullOrEmpty(list[i].SELF_CSR))
                        //    list[i].CSR = Utils.ToOnePoint(list[i].CSR);
                        //if (!string.IsNullOrEmpty(list[i].SELF_YANX_VALUE))
                        //    list[i].YANX_VALUE = list[i].SELF_YANX_VALUE;
                        list[i].BATCH_TYPE = list[i].BATCH_TYPE == "自采煤" ? "其他" : list[i].BATCH_TYPE;
                        list[i].CSR = !string.IsNullOrEmpty(list[i].SELF_CSR) ? Utils.ToOnePoint(list[i].SELF_CSR) : Utils.ToOnePoint(list[i].CSR);
                        list[i].CRI = !string.IsNullOrEmpty(list[i].SELF_CRI) ? Utils.ToOnePoint(list[i].SELF_CRI) : Utils.ToOnePoint(list[i].CRI);
                        list[i].YANX_VALUE = !string.IsNullOrEmpty(list[i].SELF_YANX_VALUE) ? list[i].SELF_YANX_VALUE : list[i].YANX_VALUE;

                    }
                    ViewBag.ID = list[0].AUDIT_ID;
                }
            return Json(new Pagination.PaginationResult<TestDataOutPutModel>(totalCount, list == null ? new List<TestDataOutPutModel>() : list.ToList()));
        }

        [HttpPost]
        [SupportFilter(ActionName = "Index OLD")]
        public JsonResult GetFlowList_OLD(GridPager pager, string testCode, string MATERIEL_ID, string startdate, string enddate, int queryState = -1, string TYPE_STR = "", string batchCode = "", string BATCH_TYPE = "")
        {
            List<V_STATS_LMS_PLAN_RESULTModel> list = m_BLL.GetList(ref pager, GetUserId(), testCode, MATERIEL_ID, startdate, enddate, "", queryState, TYPE_STR, batchCode, BATCH_TYPE);


            //foreach(var item in list)
            //{
            //    string templateid = "201805091043155860421d74303d2d1";
            //    if (item.TEMPLATE_ID != templateid)
            //    {
            //        DateTime dt = item.AUDIT_TIME.HasValue ?  item.AUDIT_TIME.Value: System.DateTime.Now;
            //        if (CreateFlow(item.AUDIT_ID, item.AUDIT_USER_ID, dt, templateid, item.TEST_CODE))
            //        {
            //            var model = m_BLL.GetItem(p => p.AUDIT_ID == item.AUDIT_ID);
            //            if (model != null)
            //            {
            //                model.APPROVAL_STATUS = (byte)2;
            //                model.TEMPLATE_ID = templateid;
            //                m_BLL.Edit(ref errors, model);
            //            }
            //        }
            //    }
            //}
            GridRows<V_STATS_LMS_PLAN_RESULTModel> grs = new GridRows<V_STATS_LMS_PLAN_RESULTModel>();
            grs.rows = list.OrderByDescending(m => m.AUDIT_TIME).ToList();
            grs.total = pager.totalRows;

            ViewBag.ID = grs.rows[0].AUDIT_ID;
            return Json(grs);
        }

        public JsonResult BatchCheck(string auditids)
        {
            string[] audit_ids = auditids.Split(',');
            string curuserid = GetUserId();
            foreach (var audit_id in audit_ids)
            {
                //获得当前步骤ID
                var formcontent = formContentBLL.GetById(audit_id);
                var curStepCheck = stepCheckBLL.GetItem(p => p.ContentId == audit_id && p.State == 2);
                var curStepCheckStateList = stepCheckStateBLL.GetList(p => p.StepCheckId == curStepCheck.Id && p.CheckFlag == 2);
                if (curStepCheck != null && formcontent != null && curStepCheckStateList != null && curStepCheckStateList.Count > 0)
                {
                    var step = stepBLL.GetById(curStepCheck.StepId);
                    //顺序下一步
                    var stepmodel = stepBLL.GetNextStepByCurStepId(curStepCheck.StepId == "00" ? "" : curStepCheck.StepId, step.FormId);
                    if (stepmodel == null)
                    {
                        //流程结束
                        var audit_model = m_BLL.GetItem(p => p.AUDIT_ID == audit_id);
                        audit_model.APPROVAL_STATUS = 3;
                        m_BLL.Edit(ref errors, audit_model);

                        formcontent.CustomMember = "";
                    }
                    else
                    {
                        var nextstepcheckmodel = stepCheckBLL.GetItem(p => p.StepId == stepmodel.Id && p.ContentId == audit_id);
                        if (nextstepcheckmodel == null)
                        {
                            //插入步骤审批表
                            nextstepcheckmodel = new Flow_FormContentStepCheckModel();
                            nextstepcheckmodel.Id = ResultHelper.NewId;
                            nextstepcheckmodel.ContentId = audit_id;
                            nextstepcheckmodel.StepId = stepmodel.Id;
                            nextstepcheckmodel.State = (int)FlowStateEnum.Progress;
                            nextstepcheckmodel.StateFlag = false;//true此步骤审批完成
                            nextstepcheckmodel.CreateTime = System.DateTime.Now;
                            nextstepcheckmodel.IsEnd = false;
                            nextstepcheckmodel.STEPNO = stepmodel.Sort;
                            nextstepcheckmodel.IsCustom = stepmodel.FlowRule == (int)FlowRuleEnum.Customer ? true : false;

                            if (stepCheckBLL.Create(ref errors, nextstepcheckmodel))//新建步骤成功
                            {
                                foreach (var userid in stepmodel.Execution.Split(','))
                                {
                                    //建立步骤审批人表
                                    Flow_FormContentStepCheckStateModel stepCheckModelState = new Flow_FormContentStepCheckStateModel();
                                    stepCheckModelState.Id = ResultHelper.NewId;
                                    stepCheckModelState.StepCheckId = nextstepcheckmodel.Id;
                                    stepCheckModelState.UserId = userid;
                                    stepCheckModelState.CheckFlag = 2;
                                    stepCheckModelState.Reamrk = "";
                                    stepCheckModelState.TheSeal = "";
                                    stepCheckModelState.CreateTime = ResultHelper.NowTime;
                                    stepCheckStateBLL.Create(ref errors, stepCheckModelState);
                                }

                                if (errors.Count > 0)
                                {
                                    stepCheckStateBLL.Deletes(ref errors, p => p.StepCheckId == nextstepcheckmodel.Id);
                                    stepCheckBLL.Deletes(ref errors, p => p.Id == nextstepcheckmodel.Id);
                                }
                                else
                                {
                                    formcontent.CustomMember = stepmodel.Execution;
                                }
                            }
                        }
                        else
                        {
                            //更新已经有步骤
                            nextstepcheckmodel.CreateTime = System.DateTime.Now;
                            nextstepcheckmodel.State = 2;
                            nextstepcheckmodel.StateFlag = false;
                            if (stepCheckBLL.Edit(ref errors, nextstepcheckmodel))
                            {
                                //更新审批人
                                foreach (var userid in stepmodel.Execution.Split(','))
                                {
                                    //建立步骤审批人表 
                                    Flow_FormContentStepCheckStateModel stepCheckModelState = stepCheckStateBLL.GetItem(p => p.StepCheckId == nextstepcheckmodel.Id && p.UserId == userid);
                                    if (stepCheckModelState == null)
                                    {
                                        //批量建立步骤审批人表 
                                        stepCheckModelState = new Flow_FormContentStepCheckStateModel();
                                        stepCheckModelState.Id = ResultHelper.NewId;
                                        stepCheckModelState.StepCheckId = nextstepcheckmodel.Id;
                                        stepCheckModelState.UserId = userid;
                                        stepCheckModelState.CheckFlag = 2;
                                        stepCheckModelState.Reamrk = "";
                                        stepCheckModelState.TheSeal = "";
                                        stepCheckModelState.CreateTime = ResultHelper.NowTime;
                                        stepCheckStateBLL.Create(ref errors, stepCheckModelState);
                                    }
                                    else
                                    {
                                        stepCheckModelState.CheckFlag = 2;
                                        stepCheckModelState.Reamrk = "";
                                        stepCheckModelState.TheSeal = "";
                                        stepCheckModelState.CreateTime = ResultHelper.NowTime;
                                        stepCheckStateBLL.Edit(ref errors, stepCheckModelState);
                                    }
                                }
                            }

                        }
                    }

                    if (errors.Count == 0)
                    {
                        curStepCheck.State = 1;
                        curStepCheck.StateFlag = true;
                        stepCheckBLL.Edit(ref errors, curStepCheck);

                        foreach (var item in curStepCheckStateList)
                        {
                            item.CheckFlag = 1;//通过
                            item.Reamrk = curuserid == item.UserId ? "同意" : "弃权";
                            item.CreateTime = ResultHelper.NowTime;
                            stepCheckStateBLL.Edit(ref errors, item);
                        }

                        formcontent.AttrY = ResultHelper.NewId;//防同一个用户审批数据没有改变
                        formContentBLL.Edit(ref errors, formcontent);
                    }

                    if (errors.Count > 0) break;

                }//curStepCheck
            }//foreach

            if (errors.Count > 0)
            {
                return Json(JsonHandler.CreateMessage(0, Resource.EditFail + errors.Error));
            }
            else
            {
                return Json(JsonHandler.CreateMessage(1, Resource.CheckSucceed));
            }
        }

        public bool CreateFlow(string id, string userid, DateTime ckeckdt, string templateid, string attrz)
        {
            //判断是否已经进入审批中
            if (formContentBLL.IsExists(id)) return false;

            //当前的Form模版
            Flow_FormModel formModel = formBLL.GetById(templateid);

            if (formModel == null) return false;

            Flow_FormContentModel model = new Flow_FormContentModel();
            model.Id = id;
            model.FormId = formModel.Id;
            model.AttrZ = attrz;
            model.CreateTime = ckeckdt;
            model.UserId = userid;
            model.Title = formModel.Name;
            model.TimeOut = ckeckdt.AddDays(30);
            model.FormLevel = "1";

            //内容提交数据库
            if (!formContentBLL.Create(ref errors, model)) return false;

            try
            {
                #region 插入起草步骤
                //插入步骤审批表
                Flow_FormContentStepCheckModel stepCheckModel0 = new Flow_FormContentStepCheckModel();
                stepCheckModel0.Id = ResultHelper.NewId;
                stepCheckModel0.ContentId = model.Id;
                stepCheckModel0.StepId = "00";
                stepCheckModel0.State = 1;
                stepCheckModel0.StateFlag = true;//true此步骤审批完成
                stepCheckModel0.CreateTime = ckeckdt;
                stepCheckModel0.IsEnd = false;
                stepCheckModel0.STEPNO = 0;
                stepCheckModel0.IsCustom = false;

                if (stepCheckBLL.Create(ref errors, stepCheckModel0))//新建步骤成功
                {
                    Flow_FormContentStepCheckStateModel stepCheckModelState = new Flow_FormContentStepCheckStateModel();
                    stepCheckModelState.Id = ResultHelper.NewId;
                    stepCheckModelState.StepCheckId = stepCheckModel0.Id;
                    stepCheckModelState.UserId = model.UserId;
                    stepCheckModelState.CheckFlag = 1;
                    stepCheckModelState.Reamrk = "申请";
                    stepCheckModelState.TheSeal = "";
                    stepCheckModelState.CreateTime = ckeckdt;
                    stepCheckStateBLL.Create(ref errors, stepCheckModelState);
                }
                #endregion

                List<Flow_StepModel> stepModelList = stepBLL.GetList(ref setNoPagerAscBySort, model.FormId);
                //查询步骤
                int listCount = stepModelList.Count();
                bool IsEnd = false;
                //循环表单的所有步骤
                for (int i = 0; i < 2; i++)
                {
                    Flow_StepModel stepModel = stepModelList[i];

                    #region 插入步骤
                    //插入步骤审批表
                    Flow_FormContentStepCheckModel stepCheckModel = new Flow_FormContentStepCheckModel();
                    stepCheckModel.Id = ResultHelper.NewId;
                    stepCheckModel.ContentId = model.Id;
                    stepCheckModel.StepId = stepModel.Id;
                    stepCheckModel.State = i == 0 ? 1 : (int)FlowStateEnum.Progress;
                    stepCheckModel.StateFlag = i == 0 ? true : false;//true此步骤审批完成
                    stepCheckModel.CreateTime = ckeckdt;
                    stepCheckModel.IsEnd = IsEnd;
                    stepCheckModel.STEPNO = stepModel.Sort;
                    stepCheckModel.IsCustom = stepModel.FlowRule == (int)FlowRuleEnum.Customer ? true : false;

                    if (stepCheckBLL.Create(ref errors, stepCheckModel))//新建步骤成功
                    {
                        if (i == 0)
                        {
                            //批量建立步骤审批人表
                            Flow_FormContentStepCheckStateModel stepCheckModelState = new Flow_FormContentStepCheckStateModel();
                            stepCheckModelState.Id = ResultHelper.NewId;
                            stepCheckModelState.StepCheckId = stepCheckModel.Id;
                            stepCheckModelState.UserId = model.UserId;
                            stepCheckModelState.CheckFlag = 1;
                            stepCheckModelState.Reamrk = "同意";
                            stepCheckModelState.TheSeal = "";
                            stepCheckModelState.CreateTime = ckeckdt;
                            stepCheckStateBLL.Create(ref errors, stepCheckModelState);
                        }
                        else
                        {
                            List<string> userIdList = GetStepCheckMemberList(stepModel.Id, model.Id);
                            for (int j = 0; j < userIdList.Count(); j++)
                            {
                                //批量建立步骤审批人表
                                Flow_FormContentStepCheckStateModel stepCheckModelState = new Flow_FormContentStepCheckStateModel();
                                stepCheckModelState.Id = ResultHelper.NewId;
                                stepCheckModelState.StepCheckId = stepCheckModel.Id;
                                stepCheckModelState.UserId = userIdList[j];
                                stepCheckModelState.CheckFlag = 2;
                                stepCheckModelState.Reamrk = "";
                                stepCheckModelState.TheSeal = "";
                                stepCheckModelState.CreateTime = ResultHelper.NowTime;
                                stepCheckStateBLL.Create(ref errors, stepCheckModelState);
                            }
                        }
                    }

                    if (IsEnd)//如果是最后一步就无需要下面继续了
                    {
                        break;
                    }
                    #endregion
                }

                return true;
            }
            catch
            {
                //创建失败，删除表单
                formContentBLL.Delete(ref errors, model.Id);
                return false;
            }

        }


        //获取步骤审批人
        public List<string> GetStepCheckMemberList(string stepId, string formContentId)
        {
            List<string> userModelList = new List<string>();
            Flow_StepModel model = stepBLL.GetById(stepId);
            if (model.FlowRule == (int)FlowRuleEnum.Lead)
            {
                SysUserModel userModel = userBLL.GetById(GetUserId());
                string[] array = userModel.Lead.Split(',');//获得领导，可能有多个领导
                foreach (string str in array)
                {
                    userModelList.Add(str);
                }
            }
            else if (model.FlowRule == (int)FlowRuleEnum.Position)
            {
                string[] array = model.Execution.Split(',');//获得领导，可能有多个领导
                foreach (string str in array)
                {
                    List<SysUserModel> userList = userBLL.GetListByPosId(str);
                    foreach (SysUserModel userModel in userList)
                    {
                        userModelList.Add(userModel.Id);
                    }
                }
            }
            else if (model.FlowRule == (int)FlowRuleEnum.Department)
            {
                GridPager pager = new GridPager()
                {
                    rows = 10000,
                    page = 1,
                    sort = "Id",
                    order = "desc"
                };
                string[] array = model.Execution.Split(',');
                foreach (string str in array)
                {
                    List<SysUserModel> userList = userBLL.GetUserByDepId(ref pager, str, "");
                    foreach (SysUserModel userModel in userList)
                    {
                        userModelList.Add(userModel.Id);
                    }
                }
            }
            else if (model.FlowRule == (int)FlowRuleEnum.Person)
            {
                string[] array = model.Execution.Split(',');//获得自选人员，可能有多个人员
                foreach (string str in array)
                {
                    userModelList.Add(str);
                }
            }
            else if (model.FlowRule == (int)FlowRuleEnum.Customer)
            {
                string users = formContentBLL.GetById(formContentId).CustomMember;
                string[] array = users.Split(',');//获得领导，可能有多个领导
                foreach (string str in array)
                {
                    userModelList.Add(str);
                }
            }
            return userModelList;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Yanx(string id)//id为AUDIT_ID
        {
            YANX_RECORD_BLL yanxBll = new YANX_RECORD_BLL();
            return View(yanxBll.GetAllList(id));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Chepai(string id)//id为BatchId
        {
            return View(m_testdataBLL.GetChepai(id));
        }

        /// <summary>
        /// 原始记录信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult OriRecord(string id)//id为BatchId
        {
            return View(m_testdataBLL.GetOriRecord(id));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Related(string textCode)//id为AUDIT_ID
        {
            SelfRcRelatedBLL yanxBll = new SelfRcRelatedBLL();
            var info = yanxBll.TestDataInfo(textCode);
            SELF_SAMPLING_RC_RELATED data = new SELF_SAMPLING_RC_RELATED();
            data.CSR = info.CSR.ToString();
            data.CRI = info.CRI.ToString();
            return View(data);
        }

        #region 详细 
        public ActionResult Details(string id)//id 为AUDIT_ID
        {
            LMS_TESTDATA_AUDITModel model = m_BLL.GetItem(a => a.AUDIT_ID == id);
            List<V_LMS_TESTDATA_CONFIRMEDModel> entity = m_cBLL.GetConfirmList(ref GridPager.NotPage, model.TEST_CODE);

            ViewBag.CheckList = entity.Where(a => a.TEST_TYPE == 0).ToList();
            ViewBag.ItemList = entity;
            ViewBag.Targets = entity.Where(a => a.TEST_TYPE > 10).Select(a => a.INDEX_ID).Distinct().ToList();
            ///
            var tempStep = stepBLL.GetNextStepByauditId(id);
            ViewBag.IsShow = tempStep == null ? 1 : 0;//是否还有后续步骤，如果是最后一级审核，放开数据勾选
            ViewBag.TEST_CODE = model.TEST_CODE;
            return View(entity);
        }

        public JsonResult GetNatureList(string index_disname)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    string strConnDB = ConfigurationManager.ConnectionStrings["OracleDbContext"].ToString();
                    string sql = $"SELECT COLLECTION_ID,INSTRUMENT,AUTO_NO,TEST_CODE,INDEX_ID,INDEX_DISNAME,TEST_VALUE,STATUS,STATUS_STR,COLLECTION_TIME,TEST_TIME,TEST_SAMPLEWEIGHT FROM V_LMS_TESTDATA_COLLECTION where TEST_CODE='{index_disname.Split('_')[0]}' and INDEX_DISNAME='{index_disname.Split('_')[1]}'";
                    System.Data.DataTable _dt = new System.Data.DataTable();
                    Oracle.ManagedDataAccess.Client.OracleDataAdapter _orcDA = new Oracle.ManagedDataAccess.Client.OracleDataAdapter(sql, strConnDB);
                    _orcDA.Fill(_dt);

                    List<V_LMS_TESTDATA_COLLECTION> list = new List<V_LMS_TESTDATA_COLLECTION>();
                    ////排序
                    if (_dt != null && _dt.Rows.Count > 0)
                    {
                        list = ValueConvert.ToDataList<V_LMS_TESTDATA_COLLECTION>(_dt);
                        list = LinqHelper.SortingAndPaging(list.AsQueryable(), "TEST_TIME", "DESC", -1, 0).ToList();
                    }
                    GridRows<V_LMS_TESTDATA_COLLECTION> grs = new GridRows<V_LMS_TESTDATA_COLLECTION>();
                    grs.rows = list;
                    grs.total = list.Count();
                    return Json(grs);
                }
            }
            catch (Exception ex)
            {
                return Json(JsonHandler.CreateMessage(0, Resource.Browse + ex.Message));
            }
        }

        #endregion 

        [HttpPost]
        public JsonResult UpdateState(string id, string templateid, int approval_status, string vals, string updatetime)
        {
            var model = m_BLL.GetById(id);
            if (model != null)
            {
                model.APPROVAL_STATUS = approval_status;
                if (!string.IsNullOrEmpty(templateid))
                {
                    model.TEMPLATE_ID = templateid;
                }
                if (approval_status == 3)
                {
                    string[] values = vals.Split(',');//1001_11,1003_14,1003_15
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    string testval = "";
                    for (int i = 0; i < values.Length; i++)
                    {
                        string[] target = values[i].Split('_');
                        if (!dic.ContainsKey(target[0]))
                        {
                            dic.Add(target[0], values[i]);
                        }
                        else
                        {
                            dic[target[0]] = dic[target[0]] + "*" + target[1];
                        }
                    }
                    foreach (var indexs in dic)
                    {
                        testval = string.IsNullOrEmpty(testval) ? indexs.Value : testval + "," + indexs.Value;
                    }
                    //List<string> list = new List<string>();
                    //for (int i = 0; i < values.Length; i++)
                    //{
                    //    if (list.Count == 0)
                    //    {
                    //        list.Add(values[i]);
                    //    }
                    //    else
                    //    {
                    //        int listIndex = list.FindIndex(a => a.IndexOf(values[i].Split('_')[0]) != -1);
                    //        if (listIndex == -1)
                    //        {
                    //            list.Add(values[i]);
                    //        }
                    //        else
                    //        {
                    //            list[listIndex] = list[listIndex] + "*" + values[i].Split('_')[1];
                    //        }
                    //    }
                    //}
                    //vals = String.Join(",", list);

                    V_LMS_RESULT_AUDIT item = new V_LMS_RESULT_AUDIT();
                    item.TEST_CODE = model.TEST_CODE;
                    item.UPDATE_TIME = DateTime.Parse(updatetime);
                    item.TEST_MODE_STR = testval;
                    item.AUDIT_USER_ID = GetUserId();

                    //这里更改了数据  在这之前就要该备份  原始化验数据 
                    if (!m_testdataBLL.BeifenTestData(model.TEST_CODE))
                    {
                        return Json(JsonHandler.CreateMessage(0, Resource.EditFail));
                    }
                    if (!m_testdataBLL.UPDATE_LMS_AUDITDATA(ref errors, item))
                    {

                        return Json(JsonHandler.CreateMessage(0, Resource.EditFail + errors.Error));
                    }
                }

                if (m_BLL.Edit(ref errors, model))
                {
                    //备份原始数据
                    return Json(JsonHandler.CreateMessage(1, Resource.ApproveSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    return Json(JsonHandler.CreateMessage(0, Resource.EditFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.EditFail));
            }
        }

    }
}
